package com.example.ui_test.ui

import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.net.Uri
import android.widget.Toast
import androidx.core.content.FileProvider
import androidx.work.ArrayCreatingInputMerger
import androidx.work.OneTimeWorkRequest
import androidx.work.WorkContinuation
import androidx.work.WorkManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.example.ui_test.R
import com.example.ui_test.adapter.MyAdapter2
import com.example.ui_test.widget.AWorker
import com.example.ui_test.widget.BWorker
import com.example.ui_test.widget.CWorker
import com.example.ui_test.widget.CustomLinearLayoutManager
import com.kun.base.ui.AbsBaseActivity
import com.kun.base.util.LogUtils
import kotlinx.android.synthetic.main.activity_ui_main.*
import java.io.File
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Method


/**
 *ui 动画相关
 *
 * @author : Kun
 * @date : 2021/7/2
 * @time : 13:34
 */
@Route(path = "/uiTest/UIMainActivity")
class UIMainActivity : AbsBaseActivity() {

    lateinit var myAdapter: MyAdapter2
    override fun getLayoutId(): Int {
        return R.layout.activity_ui_main
    }

    override fun initViewModel() {
        val requestA = OneTimeWorkRequest.Builder(AWorker::class.java).build()
        val requestB = OneTimeWorkRequest.Builder(BWorker::class.java).build()
        val requestC = OneTimeWorkRequest.Builder(CWorker::class.java)
            .setInputMerger(ArrayCreatingInputMerger::class.java)
            .build()
        val continuationA = WorkManager.getInstance(this).beginWith(requestA)
        val continuationB = WorkManager.getInstance(this).beginWith(requestB)

        val list = mutableListOf(continuationA, continuationB);

        WorkContinuation.combine(list).then(requestC).enqueue()
    }

    override fun initView() {
        rcl()
        btn_animal.setOnClickListener {
            ARouter.getInstance().build("/uiTest/TransitionAnimalActivity").navigation()
        }
        btn_color.setOnClickListener {
            ARouter.getInstance().build("/uiTest/ColorActivity").navigation()
        }

        val intent = intent
        val action = intent.action
        val type = intent.type

        LogUtils.e("type-----$type")
        if (Intent.ACTION_SEND == action) {
            val uri = intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM)
            Toast.makeText(this, uri.toString(), Toast.LENGTH_SHORT).show()
            LogUtils.e("uri_path-----" + uri.toString())
            LogUtils.e("uri_scheme-----" + uri?.scheme)

            val path = getFilePathByUri(this, uri!!)
            LogUtils.e("getFilePathByUri-----$path")

            val file = File(path!!)
            LogUtils.e("-------文件:" + file.name + "," + file.length())
            //context.getContentResolver().openInputStream(uri)

            if (ContentResolver.SCHEME_CONTENT == uri.scheme) {

                val query = contentResolver.query(uri, null, null, null, null)
                if (query != null) {
                    query.moveToFirst()
                    for (t in query.columnNames) {
                        LogUtils.e("ttt--------$t")

                        LogUtils.e("ddd------" + query.getString(query.getColumnIndex(t)))
                    }

                    query.close()
                }
            }
        }
    }

    /**
     * 7.0以上 文件 Uri 转绝对路径
     */
    private fun getFilePathByUri(context: Context, uri: Uri): String? {
        var path: String? = null
        val packs: List<PackageInfo> =
            context.packageManager.getInstalledPackages(PackageManager.GET_PROVIDERS)
        val fileProviderClassName: String = FileProvider::class.java.name
        for (pack in packs) {
            val providers = pack.providers
            if (providers != null) {
                for (provider in providers) {
                    if (uri.authority == provider.authority) {
                        if (provider.name.equals(fileProviderClassName, ignoreCase = true)) {
                            val fileProviderClass: Class<FileProvider> =
                                FileProvider::class.java
                            try {
                                val getPathStrategy: Method =
                                    fileProviderClass.getDeclaredMethod(
                                        "getPathStrategy",
                                        Context::class.java,
                                        String::class.java
                                    )
                                getPathStrategy.isAccessible = true
                                val invoke: Any? =
                                    getPathStrategy.invoke(null, context, uri.authority)
                                if (invoke != null) {
                                    val pathStrategyStringClass: String =
                                        FileProvider::class.java.name + "\$PathStrategy"
                                    val pathStrategy = Class.forName(pathStrategyStringClass)
                                    val getFileForUri: Method = pathStrategy.getDeclaredMethod(
                                        "getFileForUri",
                                        Uri::class.java
                                    )
                                    getFileForUri.isAccessible = true
                                    val invoke1: Any? = getFileForUri.invoke(invoke, uri)
                                    if (invoke1 is File) {
                                        path = invoke1.absolutePath
                                    }
                                }
                            } catch (e: NoSuchMethodException) {
                                e.printStackTrace()
                            } catch (e: InvocationTargetException) {
                                e.printStackTrace()
                            } catch (e: IllegalAccessException) {
                                e.printStackTrace()
                            } catch (e: ClassNotFoundException) {
                                e.printStackTrace()
                            }
                            break
                        }
                        break
                    }
                }
            }
        }
        return path
    }

    fun rcl() {
        myAdapter = MyAdapter2(this, null)

//        rcl.layoutManager = LinearLayoutManager(this)
        rcl.layoutManager = CustomLinearLayoutManager(this)
        rcl.adapter = myAdapter

        val data = mutableListOf("asd", "asddsf", "1", "2", "3", "4", "5", "6", "7", "8")
        myAdapter.setList(data)

        rcl.start()
    }
}